<?php
class IndexController extends CommonController {
	public function index() {
		if(isset($_GET['openid'])){
			$_SESSION['user']['openid']=$_GET['openid'];
		}
		$this->assign ( 'slider', M ( 'Slider' )->order ( 'sort asc' )->select () );
		$this->assign ( 'news_list', M ( 'News' )->where ( "is_home='1'" )->order ( 'id desc' )->select () );
		$this->dispaly ();
	}
	public function sendSms() {
		$phone = $_GET ['phone'];
		$time = strtotime ( date ( 'Y-m-d' ) );
		$count = M ( 'SmsLog' )->where ( "phone='{$phone}' and create_time>={$time}" )->count ();
		if ($count >= 3) {
			$rs ['status'] = 2;
			$rs ['msg'] = '今天你能使用的短信已经用完,请明天再来';
			exit ( json_encode ( $rs ) );
		}
		$userShareLog = M ( 'UserShareLog' )->where ( "tel='{$phone}'" )->find ();
		if (! empty ( $userShareLog )) {
			$rs ['status'] = 3;
			$rs ['msg'] = '该手机号已经使用过了';
			exit ( json_encode ( $rs ) );
		}
		$data ['phone'] = $phone;
		$_SESSION ['code'] = $data ['code'] = String::randString(4,1);
		if(Sms::sendMsg($phone,$data['code'])){
			$data ['create_time'] = $_SERVER ['REQUEST_TIME'];
			M ( 'SmsLog' )->save ( $data );
			$rs ['status'] = 1;
		}else{
			$rs['status']=4;
			$rs['msg']='发送短信失败';
		}
		echo json_encode ( $rs );
	}
	public function login() {
		if ($this->isGet ()) {
			$user = M ( 'User' )->field ( 'username' )->where ( "id=" . intval ( $_GET ['uid'] ) )->find ();
			$this->assign ( 'user', $user );
			$this->display ();
		} else {
			$phone = trim ( $_POST ['phone'] );
			$code = trim ( $_POST ['code'] );
			if ($code != $_SESSION ['code']) {
				$rs ['status'] = 2;
				$rs ['msg'] = '验证码不正确';
				exit ( json_encode ( $rs ) );
			}
			$user = is_user ( $phone );
			if ($user ['status'] == 1) {
				$user ['username'] = $user ['username'];
				$user ['card'] = $user ['card'];
			} else {
				$maxUser = M ( 'User' )->field ( 'card' )->order ( 'card desc' )->find ();
				$start_card = 900001;
				if (empty ( $maxUser )) {
					$card = $start_card;
				} else if (intval ( $maxUser ['card'] ) < $start_card) {
					$card = $start_card;
				} else {
					$card = intval ( $maxUser ['card'] ) + 1;
					if (substr ( $card ) == 4 || substr ( $card, - 1 ) == 7) {
						++ $card;
					}
				}
				$user ['card'] = $card;
			}
			$user ['tel'] = $phone;
			$user ['create_time'] = $_SERVER ['REQUEST_TIME'];
			$user ['bonus'] = 10;
			$id = M ( 'User' )->save ( $user );
			$user ['id'] = $id;
			unset ( $_SESSION ['code'] );
			$rs ['status'] = 1;
			$uid = intval ( $_POST ['uid'] );
			$user_share_log ['uid'] = $uid;
			$user_share_log ['user_id'] = $user ['id'];
			$user_share_log ['create_time'] = $_SERVER ['REQUEST_TIME'];
			$user_share_log ['tel'] = $phone;
			M ( 'UserShareLog' )->save ( $user_share_log );
			userBonus ( $uid, 10 );
			echo json_encode ( $rs );
		}
	}
}